package net.lanelife.casino.caipiao.service;

import java.util.Map;

import javax.persistence.Query;

import net.lanelife.casino.caipiao.entity.User;
import net.lanelife.casino.caipiao.entity.statistics.UserStatistics;
import net.lanelife.casino.caipiao.repository.api.IUserStatisticsRepository;
import net.lanelife.casino.caipiao.service.api.IUserStatisticsService;
import net.lanelife.casino.common.repository.support.GenericRepository;
import net.lanelife.casino.common.service.support.GenericService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserStatisticsService extends GenericService<UserStatistics, Integer> implements IUserStatisticsService {

	@Autowired
	private IUserStatisticsRepository repository;
	
	public UserStatisticsService() {
		super(UserStatistics.class);
	}
	
	@Override
	protected GenericRepository<UserStatistics, Integer> getRepository() {
		return repository;
	}

	/**
	 * 创建用户统计表
	 * @param user
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public UserStatistics create(User user) throws Exception {
		UserStatistics ts = new UserStatistics(user);
		repository.save(ts);
		return ts;
	}

	/**
	 * 更新用户统计表
	 * @param user
	 * @param properties
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public int update(User user, Map<String, Object> properties) throws Exception {
		StringBuilder sql = new StringBuilder("UPDATE TB_USER_STATISTICS SET VERSION=VERSION+1,");
		for (String property : properties.keySet()) {
			sql.append(property).append("=").append(property).append("+:").append(property).append(",");
		}
		sql.replace(sql.length()-1, sql.length(), " ");
		sql.append("WHERE USER_ID=:USER_ID");
		Query query = em.createNativeQuery(sql.toString());
		query.setParameter("USER_ID", user.getId());
		for (String property : properties.keySet()) {
			query.setParameter(property, properties.get(property));
		}
		return query.executeUpdate();
	}

	
}
